package com.atguigu.dga.ds.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.dga.ds.bean.TDsTaskDefinition;
import com.atguigu.dga.ds.bean.TDsTaskInstance;
import com.atguigu.dga.ds.mapper.TDsTaskDefinitionMapper;
import com.atguigu.dga.ds.service.TDsTaskDefinitionService;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zhangchen
 * @since 2023-07-03
 */
@Service
@DS("ds")
public class TDsTaskDefinitionServiceImpl extends ServiceImpl<TDsTaskDefinitionMapper, TDsTaskDefinition> implements TDsTaskDefinitionService {

    @Override
    public List<TDsTaskDefinition> getTaskDefinitionListForAssess(List<TDsTaskInstance> tDsTaskInstanceList) {
        // 1 根据 实例code 提取任务定义
        List<Long> taskCodeList = tDsTaskInstanceList.stream().map(tDsTaskInstance -> tDsTaskInstance.getTaskCode()).collect(Collectors.toList());
        List<TDsTaskDefinition> tDsTaskDefinitionList = list(new QueryWrapper<TDsTaskDefinition>().in("code", taskCodeList));
        //2  根据定义中的参数 提取 sql语句
        for (TDsTaskDefinition tDsTaskDefinition : tDsTaskDefinitionList) {
            String sql=  extractSQL( tDsTaskDefinition.getTaskParams());
            tDsTaskDefinition.setSql(sql);
        }

        return tDsTaskDefinitionList;
    }

    private String extractSQL(String taskParams) {
        //1  解析为json对象
        JSONObject taskParamJsonObj = JSON.parseObject(taskParams);
        //2  从json中提取脚本
        String rawScriptShell = taskParamJsonObj.getString("rawScript");
        //3  从脚本中提取sql
        // 起始位置坐标
        int startIdx = rawScriptShell.indexOf("with");
        if(startIdx==-1){
            startIdx=rawScriptShell.indexOf("insert");
        }
        // 结束位置
        int  endIdx=  rawScriptShell.indexOf(";",startIdx);
        if(endIdx==-1){
            endIdx=rawScriptShell.indexOf("\"",startIdx);
        }
        String sql = rawScriptShell.substring(startIdx, endIdx).replace("\n"," ");


        return sql;
    }
}
